package com.heima.user.interceptor;

import com.heima.model.admin.pojos.AdUser;
import com.heima.utils.thread.AdminThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName: AdminTokenInterceptor
 * Description:
 * date: 2023/8/21 0021 21:25
 *
 * @author zHan
 */
public class AdminTokenInterceptor implements HandlerInterceptor {

    /**
     * 得到用户信息，并存入当前线程中
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        // 得到管理员信息
        String adminId = request.getHeader("adminId");
        if (adminId != null) {
            // 存入当前线程中
            AdUser adUser = new AdUser();
            adUser.setId(Integer.valueOf(adminId));
            AdminThreadLocalUtil.setUser(adUser);
        }

        // 放行
        return true;
    }

    /**
     * 清理线程中数据
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        AdminThreadLocalUtil.clear();
    }
}
